package com.example.customviewtouch

import android.R
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.customviewtouch.downfresh.adapter.RefreshHeaderAdapter
import com.example.customviewtouch.downfresh.view.RefreshHeaderRecyclerView


class MainActivity : AppCompatActivity() {

    private val mStringList: MutableList<String> = ArrayList()
    private var mRecyclerView: RefreshHeaderRecyclerView? = null
    private var mAdapter: RefreshHeaderAdapter? = null
    private val FINISH = 1

    private val sHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what === FINISH) {
                Toast.makeText(this@MainActivity, "刷新完成！", Toast.LENGTH_SHORT).show()
                mRecyclerView!!.refreshComplete()
            }
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(com.example.customviewtouch.R.layout.activity_main)
        initData()
        setupRecyclerView()
    }

    private fun setupRecyclerView() {
        mRecyclerView = findViewById<RefreshHeaderRecyclerView>(com.example.customviewtouch.R.id.recyclerView)
        mAdapter = RefreshHeaderAdapter(mStringList)
        mRecyclerView?.setRefreshHeaderAdapter(mAdapter!!)
        mRecyclerView?.setOnRefreshListener(object :
            com.example.customviewtouch.downfresh.interfaces.OnRefreshListener {
            override fun onRefresh() {
                requestData()
            }
        })
        mRecyclerView?.layoutManager = LinearLayoutManager(this)
    }

    private fun requestData() {
        Thread {
            this@MainActivity.toString()
            try {
                Log.d("ZZZyt", "Thread.sleep before")
                Thread.sleep(1500)
                Log.d("ZZZyt", "Thread.sleep after")
                val message = Message.obtain()
                message.what = FINISH
                sHandler.sendMessage(message)
            } catch (e: InterruptedException) {
                Log.d("ZZZyt", "e = $e")
                e.printStackTrace()
            }
        }.start()
    }
    private fun initData() {
        for (i in 0..14) {
            mStringList.add("")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        sHandler.removeCallbacksAndMessages(null)
    }

}